package com.spring.web.adminmanage.service.impl;

import com.github.pagehelper.PageHelper;
import com.spring.web.adminmanage.entities.Menu;
import com.spring.web.adminmanage.repository.MenuDao;
import com.spring.web.adminmanage.service.MenuService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by chenwenhao on 2017/6/28.
 */
@Service
public class MenuServiceImpl implements MenuService {


    @Autowired
    private MenuDao menuDao;

    /**
     * 获取菜单列表
     * @return
     */
    @Override
    public List<Menu> getMenu(String pId) {
        return  menuDao.getAllMenu(pId);
    }
    /**
     * 通过id删除菜单
     * @param id
     */
    @Override
    public int delete(Long id) {
        return menuDao.deleteByPrimaryKey(id);
    }


    @Override
    public List<Menu> selectToPageResult( String searchText ,String pid){
        PageHelper.orderBy("scort asc");
        Example example = new Example(Menu.class);
        Example.Criteria criteria = example.createCriteria();
        if (StringUtils.isNotBlank(searchText)) {
            criteria.andLike("name", "%"+searchText+"%");
        }
        if(StringUtils.isNotBlank(pid)){
            criteria.andEqualTo("pid",pid);
        }
        return menuDao.selectByExample(example);
    }

    @Override
    public Menu getMenuById(Long id) {
        return menuDao.selectByPrimaryKey(id);
    }

    @Override
    public void addMenu(Menu menu) {
        menuDao.insert(menu);
    }

    @Override
    public void update(Menu menu) {
        menuDao.updateByPrimaryKey(menu);
    }

    @Override
    public List<Menu> getMenuAll() {
        return menuDao.selectAll();
    }

    @Override
    public List<Menu> getMenuByRoleId(String roleId) {
        List<Menu> userMenuList = new ArrayList<Menu>();
        List<Menu> secondLevelMenuList = new ArrayList<Menu>();
        List<Menu> menuList = menuDao.getMenuByRoleId(roleId);
        for(Menu menu : menuList){
            if("0".equals(menu.getPid())){
                userMenuList.add(menu);
            }else{
                secondLevelMenuList.add(menu);
            }
        }
        for(Menu uml : userMenuList){
            List<Menu> menuItem = new ArrayList<Menu>();
            for(Menu secondLevelMenu : secondLevelMenuList){
                if(secondLevelMenu.getPid().equals(uml.getId().toString()) ){
                    menuItem.add(secondLevelMenu);
                }
            }
            uml.setMenuItem(menuItem.size() > 0 ? menuItem : null );
        }
        return userMenuList;
    }

}

